package com.hongawen.unsafe;

import cn.hutool.core.util.StrUtil;
import lombok.SneakyThrows;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2021年09月01日 09:09
 */
public class UnsafeByTicket {

    public static void main(String[] args) {
        Station station = new Station();

        new Thread(station,"小黄").start();
        new Thread(station,"小红").start();
        new Thread(station,"小蓝").start();

    }
}


/**
 * 车站
 */
class Station implements Runnable {

    int ticketNumbers = 10;

    boolean flag = true;


    @Override
    public void run() {
        while(flag){
            buy();
        }
    }

    @SneakyThrows
    synchronized void buy(){
        if (ticketNumbers <= 0) {
            flag = false;
            System.out.println("车票已售罄");
            return;
        }
        Thread.sleep(100);
        System.out.println(StrUtil.format("{}来车站买票，买到了{}号票", Thread.currentThread().getName(), ticketNumbers--));
    }
}